package com.yuanian.timingwheel.model.timingwheel;

import com.alibaba.fastjson.JSONObject;
import com.yuanian.timingwheel.annotation.scan.TimingTaskScanner;
import com.yuanian.timingwheel.model.task.base.BaseTask;
import com.yuanian.timingwheel.model.task.executetask.LocalTaskExecutor;
import com.yuanian.timingwheel.respository.po.TaskEntity;

import java.util.LinkedHashMap;
import java.util.List;

/**
 * 定时任务加载器
 */
public class TaskLoader extends TimingTaskScanner {

    /**
     * 实体转化
     * @param taskEntity
     * @return
     */
    protected BaseTask taskEntity2BaseTask(TaskEntity taskEntity) {
        BaseTask task = new BaseTask(taskEntity.getBusinessId(), taskEntity.getExecutionInterval(), taskEntity.getExecutionRounds(), taskEntity.getExecutedRounds(), taskEntity.getExecutionTime(), taskEntity.getTaskDesc());
        task.setTaskMethod(new LocalTaskExecutor(taskEntity.getTaskMethod().getExecutionMethod(), taskEntity.getTaskMethod().getBeanName(), taskEntity.getTaskMethod().getArgs(), taskEntity.getTaskMethod().getParamClazz()));
        task.setStatus(taskEntity.getStatus());
        if (taskEntity.getId() != null) {
            task.setId(taskEntity.getId());
        }
        //增加附加任务
        List<TaskEntity> attachTaskList = taskEntity.getAttachTaskList();
        if (attachTaskList != null) {
            for (int i = 0; i < attachTaskList.size(); i++) {
                Object obj = attachTaskList.get(i);
                if (obj instanceof TaskEntity) {
                    task.addAttachTask(taskEntity2BaseTask((TaskEntity)(obj)));
                } else if (obj instanceof LinkedHashMap) {//从数据库取出的JSON需要转换成实体
                    LinkedHashMap map = (LinkedHashMap)obj;
                    Object taskMethodMap = map.get("taskMethod");
                    BaseTask baseTask = getTaskEntity(obj);
                    baseTask.setTaskMethod(getTaskMethod(taskMethodMap));
                    task.addAttachTask(baseTask);
                }
            }
        }
        return task;
    }

    private LocalTaskExecutor getTaskMethod(Object obj) {
        return JSONObject.parseObject(JSONObject.toJSONString(obj), LocalTaskExecutor.class);
    }

    private BaseTask getTaskEntity(Object obj) {
        return JSONObject.parseObject(JSONObject.toJSONString(obj), BaseTask.class);
    }

}
